﻿
// DemoDlg.cpp: 实现文件
//
#include "pch.h"
#include "framework.h"
#include "Demo.h"
#include "MainDlg.h"
#include "afxdialogex.h"
#include <MvErrorDefine.h>


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

	// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum
	{
		IDD = IDD_ABOUTBOX
	};
#endif

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{

	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CDemoDlg 对话框

CMainDlg::CMainDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_MAIN_DIALOG, pParent),
	m_logBuffer(500)
	, m_bCancleFalg(FALSE)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMainDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST_LOG, m_LogList);
	DDX_Control(pDX, IDC_COMBO_CAMLIST, m_comboCamList);
}

BEGIN_MESSAGE_MAP(CMainDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_MESSAGE(WM_SEND_LOG_MSG_TO_MAIN_UI, &CMainDlg::OnReceiveAndDisplaySystemLog)
	ON_NOTIFY(NM_CUSTOMDRAW, IDC_LIST_LOG, &CMainDlg::OnNMCustomdrawListLog)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST_LOG, &CMainDlg::OnLvnItemchangedListLog)
	ON_COMMAND(ID_OPC_TCPIP, &CMainDlg::OnOpcTcpip)
	ON_COMMAND(ID_CMERA, &CMainDlg::OnCmera)
	ON_BN_CLICKED(IDC_BUTTON_STOP, &CMainDlg::OnBnClickedButtonStop)
	ON_BN_CLICKED(IDC_BUTTON_INIT, &CMainDlg::OnBnClickedButtonInit)
	ON_WM_CTLCOLOR()
	ON_WM_TIMER()
	ON_COMMAND(ID_LOGIN, &CMainDlg::OnLogin)
	ON_COMMAND(ID_BTN_CHANGE_PROJECT, &CMainDlg::OnBtnChangeProject)
	ON_WM_SIZE()
	ON_COMMAND(ID_GLUE_TEST, &CMainDlg::OnGlueTest)
	ON_BN_CLICKED(IDC_BUTTON_TEST_HAND, &CMainDlg::OnBnClickedButtonTestHand)
	ON_BN_CLICKED(IDC_BUTTON1, &CMainDlg::OnBnClickedButton1)
END_MESSAGE_MAP()


// CDemoDlg 消息处理程序

BOOL CMainDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();
	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	int nStyle;
	// TODO: 在此添加额外的初始化代码
	m_LogList.SetBkColor(RGB(200, 220, 250));
	//m_LogList.SetBkColor(TRANSPARENT);
	//m_LogList.SetTextColor(RGB(250, 250, 250));
	nStyle = GetWindowLong(m_LogList.m_hWnd, GWL_STYLE);
	nStyle &= ~LVS_TYPEMASK;
	nStyle |= LVS_REPORT;
	SetWindowLong(m_LogList.m_hWnd, GWL_STYLE, nStyle);
	m_LogList.ShowWindow(SW_SHOW);
	DWORD dwStyle = m_LogList.GetExtendedStyle();
	dwStyle |= LVS_EX_FULLROWSELECT;
	dwStyle |= LVS_EX_GRIDLINES;
	dwStyle |= LVS_EX_INFOTIP;

	m_LogList.SetExtendedStyle(dwStyle);
	m_LogList.SetFont(&gSystemMgr.m_logFont);
	m_LogList.EnableWindow(TRUE);
	m_LogList.InsertColumn(0, L"当前时刻", LVCFMT_LEFT, 300 / 10 * 3);
	m_LogList.InsertColumn(1, L"日志详细描述", LVCFMT_LEFT, 300 / 10 * 20);
	m_LogList.ShowWindow(SW_HIDE);
	m_LogList.EnableWindow(TRUE);
	m_LogList.Invalidate();
	m_LogList.ShowWindow(SW_SHOW);
	m_LogList.BringWindowToTop();
	gSystemMgr.m_logFont.DeleteObject();

	m_menu.LoadMenuW(IDR_MAIN_MENU);
	this->SetMenu(&m_menu);
	SetUiHandle();

	for (int i = 0; i < THREAD_NUM; i++)
	{
		CloseHandle(ThreadHandle[i]);
	}
	gSystemMgr.GeneralSettingIniInit();
	gSystemMgr.SystemInfIniInit();
	gSystemMgr.CameraSettingIniInit();
	gSystemMgr.LoginConfigIniInit();//Login信息
	MainDlgInfIniInit();


	CWnd *pWnd;//主窗口控件
	{
		int n = 0;

		n = n + 1; pWnd = GetDlgItem(IDC_STATIC_1); pWnd->GetWindowRect(&OriRect[n]); RectW[n] = OriRect[n].right - OriRect[n].left; RectH[n] = OriRect[n].bottom - OriRect[n].top;
		n = n + 1; pWnd = GetDlgItem(IDC_COMBO_CAMLIST); pWnd->GetWindowRect(&OriRect[n]); RectW[n] = OriRect[n].right - OriRect[n].left; RectH[n] = OriRect[n].bottom - OriRect[n].top;
		n = n + 1; pWnd = GetDlgItem(IDC_SHOW_IMAGE); pWnd->GetWindowRect(&OriRect[n]); RectW[n] = OriRect[n].right - OriRect[n].left; RectH[n] = OriRect[n].bottom - OriRect[n].top;
		n = n + 1; pWnd = GetDlgItem(IDC_STATIC_2); pWnd->GetWindowRect(&OriRect[n]); RectW[n] = OriRect[n].right - OriRect[n].left; RectH[n] = OriRect[n].bottom - OriRect[n].top;
		n = n + 1; pWnd = GetDlgItem(IDC_LINK_PLC); pWnd->GetWindowRect(&OriRect[n]); RectW[n] = OriRect[n].right - OriRect[n].left; RectH[n] = OriRect[n].bottom - OriRect[n].top;
		n = n + 1; pWnd = GetDlgItem(IDC_STATIC_CAM_STATUS); pWnd->GetWindowRect(&OriRect[n]); RectW[n] = OriRect[n].right - OriRect[n].left; RectH[n] = OriRect[n].bottom - OriRect[n].top;
		n = n + 1; pWnd = GetDlgItem(IDC_LIST_LOG); pWnd->GetWindowRect(&OriRect[n]); RectW[n] = OriRect[n].right - OriRect[n].left; RectH[n] = OriRect[n].bottom - OriRect[n].top;
		n = n + 1; pWnd = GetDlgItem(IDC_STATIC_3); pWnd->GetWindowRect(&OriRect[n]); RectW[n] = OriRect[n].right - OriRect[n].left; RectH[n] = OriRect[n].bottom - OriRect[n].top;
		n = n + 1; pWnd = GetDlgItem(IDC_EDIT_RESULT_SHOW); pWnd->GetWindowRect(&OriRect[n]); RectW[n] = OriRect[n].right - OriRect[n].left; RectH[n] = OriRect[n].bottom - OriRect[n].top;
		n = n + 1; pWnd = GetDlgItem(IDC_BUTTON_TEST_HAND); pWnd->GetWindowRect(&OriRect[n]); RectW[n] = OriRect[n].right - OriRect[n].left; RectH[n] = OriRect[n].bottom - OriRect[n].top;
		
	}
	GetClientRect(&m_rcUiRect);

	CRect rcScreen;
	SystemParametersInfo(SPI_GETWORKAREA, 0, &rcScreen, 0);
	int m_nCrtScreenWidth = rcScreen.Width() / 2;
	int m_nCrtScreenHeight = rcScreen.Height() / 2;
	::SetWindowPos(m_hWnd, HWND_TOP, m_nCrtScreenWidth * 0, m_nCrtScreenHeight * 0, m_nCrtScreenWidth, m_nCrtScreenHeight, SWP_SHOWWINDOW);
	StartGigeCamAutoLink();
	gSystemMgr.TcpIpConnect();
	gSystemMgr.StartTcpipRecvThread();
	gSystemMgr.StartGlueTestThread();
	//SetTimer(TIMER_ID_MAIN_STATUS, 500, NULL);
	SetWindowText(L"胶水检测-v1.4");
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}
void CMainDlg::StartGigeCamAutoLink()
{
	CamLink.MemProc = &CMainDlg::GigeCamAutoLink;
	UINT nThreadId;
	HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, CamLink.ThreadProc, (LPVOID)this, 0, &nThreadId);
	if (hThread == NULL)
	{
		gSystemLog.DisplayLogAndSave(L"Create start thread fail", LV_ERROR);
	}
}

unsigned int __stdcall CMainDlg::GigeCamAutoLink()
{
	int cnt = 100;
	while (true)
	{
		Sleep(50);
		cnt++;
		if (cnt < 100)
			continue;
		cnt = 0;
		if (gSystemMgr.m_cGigeCam.m_bStartGrabbing) continue;
		bool nflag = EnumCamera();
		if (nflag)
		{
			nflag = OnBnClickedButtonStart();
			if (nflag)
			{
				SetDlgItemTextW(IDC_STATIC_CAM_STATUS, L"OK");
				gSystemMgr.CameraFlag = 1;
			}
			else
			{
				SetDlgItemTextW(IDC_STATIC_CAM_STATUS, L"FAIL"); 
				gSystemMgr.CameraFlag = 0;
			}
		}
		else
		{
			SetDlgItemTextW(IDC_STATIC_CAM_STATUS, L"FAIL"); 
			gSystemMgr.CameraFlag = 0;
		}
	}
}

int CMainDlg::EnumCamera()
{
	m_comboCamList.ResetContent();
	auto flag = gSystemMgr.m_cGigeCam.GigECamInit();

	if (flag == 1)
	{
		for (size_t i = 0; i < gSystemMgr.m_cGigeCam.m_stDevList.nDeviceNum; i++)
		{
			m_comboCamList.AddString(gSystemMgr.m_cGigeCam.m_cstrGigeCamEnumName[i]);
			if (gSystemMgr.m_cGigeCam.m_cstrGigeCamEnumName[i] == gSystemMgr.m_sCameraInf.m_cCameraInfo)
			{
				m_comboCamList.SetCurSel(i);
				break;
			}
			if (i == gSystemMgr.m_cGigeCam.m_stDevList.nDeviceNum - 1)
			{
				gSystemLog.DisplayLogAndSave(L"未检测到选择的相机！", LV_ERROR);
			}
		}
		return 1;
	}
	else
	{
		//gSystemLog.DisplayLogAndSave(L"未检测到相机！", LV_ERROR);
		return 0;
	}
}
void CMainDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}


// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CMainDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CMainDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

LRESULT CMainDlg::OnReceiveAndDisplaySystemLog(WPARAM wParam, LPARAM lParam)
{
	eEVENT_LEVEL   logLevel = LV_EVENT;;
	CString cstrp = (BSTR)wParam;
	SysFreeString((BSTR)wParam);
	switch (lParam)
	{
	case(LV_EVENT):
		logLevel = LV_EVENT;
		break;
	case(LV_WARNING):
		logLevel = LV_WARNING;
		break;
	case(LV_ERROR):
		logLevel = LV_ERROR;
		break;
	default:
		break;
	}
	wstring wstrLogMsg = cstrp.GetString();
	std::vector<wstring> vLogItem = _utils::SplitString(wstrLogMsg, L"#");
	if (vLogItem.size() != 2)
	{
		return 0;
	}
	wstring wstrTime = vLogItem[0];
	wstring wstrMsg = vLogItem[1];
	int nIndexItem = m_LogList.GetItemCount();
	m_LogList.InsertItem(0, L"");
	m_LogList.SetItemText(0, 0, wstrTime.c_str());
	m_LogList.SetItemText(0, 1, wstrMsg.c_str());
	LOG_PACKAGE logPackage;
	logPackage.m_level = logLevel;
	logPackage.m_wstrTime = wstrTime;
	logPackage.m_wstrMsg = wstrMsg;
	m_logBuffer.push_back(logPackage);
	m_LogList.Invalidate();
	if (nIndexItem >= 500)
	{
		m_LogList.DeleteItem(500);
	}
	return 0;
}


void CMainDlg::SetUiHandle()
{
	CMenu* pUIMenu = GetMenu();
	pUIMenu = AfxGetMainWnd()->GetMenu();
	/*pUIMenu->EnableMenuItem(ID_BTN_PLC, MF_DISABLED);
	pUIMenu->EnableMenuItem(ID_OPC_TCPIP, MF_DISABLED);
	pUIMenu->EnableMenuItem(ID_CMERA, MF_DISABLED);
	pUIMenu->EnableMenuItem(ID_MATCH_TEMPLATE, MF_DISABLED);
	pUIMenu->EnableMenuItem(ID_32783, MF_DISABLED);*/

	gSystemLog.m_hUiHandle = this->GetSafeHwnd();
	HWND_MAIN = this->GetSafeHwnd();
	gSystemMgr.m_ptrMainUI = this;

}


void CMainDlg::OnCancel()
{
	// TODO: 在此添加专用代码和/或调用基类

	KillTimer(TIMER_ID_MAIN_STATUS);
	OnBnClickedButtonStop();
	Sleep(500);
	gSystemMgr.m_cGigeCam.CloseDevice();//停止采集
	gSystemMgr.m_cTcpIp.CloseSocketServer();

	delete m_cDlgMain;
	delete m_cTcpipDlg;
	delete m_cGigeCamSettingDlg;
	delete m_cGlueTestDlg;
	m_cDlgMain = nullptr;
	m_cTcpipDlg = nullptr;
	m_cGigeCamSettingDlg = nullptr;
	m_cGlueTestDlg = nullptr;

	CDialogEx::OnCancel();
}



void CMainDlg::MainDlgInfIniInit()
{
	char cDir[MAX_PATH];
	m_cMainConfigIni.GetCurrentDir((LPWSTR)cDir);
	CString cstr;
	cstr.Format(L"%s\\recipe\\Login.ini", cDir);
	m_cMainConfigIni.ConfigIniInit(cstr);
}



void CMainDlg::OnLvnItemchangedListLog(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
	// TODO: 在此添加控件通知处理程序代码
	*pResult = 0;
}

void CMainDlg::OnNMCustomdrawListLog(NMHDR *pNMHDR, LRESULT *pResult)
{
	NMLVCUSTOMDRAW* lplvcd = reinterpret_cast<NMLVCUSTOMDRAW*>(pNMHDR);
	int nIRow = int(lplvcd->nmcd.dwItemSpec);
	if (lplvcd->nmcd.dwDrawStage == CDDS_PREPAINT)
	{
		*pResult = CDRF_NOTIFYITEMDRAW;
		return;
	}
	if (lplvcd->nmcd.dwDrawStage == CDDS_ITEMPREPAINT)
	{
		lplvcd->clrTextBk = RGB(200, 220, 250);
		//lplvcd->clrTextBk =TRANSPARENT;
		*pResult = CDRF_NOTIFYSUBITEMDRAW;
		return;
	}
	else if (lplvcd->nmcd.dwDrawStage == (CDDS_SUBITEM | CDDS_PREPAINT | CDDS_ITEMPREPAINT))
	{
		COLORREF crText = RGB(10, 10, 10);
		if (lplvcd->iSubItem == 1)
		{
			LOG_PACKAGE logPackage;
			logPackage = m_logBuffer.at(m_LogList.GetItemCount() - nIRow - 1);
			switch (logPackage.m_level)
			{
			case(LV_ERROR):
				crText = RGB(250, 0, 0);
				break;
			case(LV_WARNING):
				crText = RGB(150, 150, 0);
				break;
			case(LV_EVENT):
				crText = RGB(50, 50, 50);
				break;
			default:
				break;
			}
			lplvcd->clrText = crText;
			*pResult = CDRF_DODEFAULT;
			return;
		}
	}
	*pResult = 0;
}


void CMainDlg::OnLogin()
{
	if (m_cLoginDlg != nullptr)
	{
		m_cLoginDlg->ShowWindow(SW_SHOW);
	}
	if (m_cLoginDlg == nullptr)
	{
		m_cLoginDlg = new CLoginDlg;
		m_cLoginDlg->Create(IDD_DIALOG_LOGIN, this);
	}
	m_cLoginDlg->ShowWindow(SW_SHOW);
}

void CMainDlg::OnOpcTcpip()
{
	if (m_cTcpipDlg != nullptr)
	{
		delete m_cTcpipDlg;
		m_cTcpipDlg = nullptr;
	}
	if (m_cTcpipDlg == nullptr)
	{
		m_cTcpipDlg = new CTcpipDlg;
		m_cTcpipDlg->Create(IDD_DIALOG_TCPIP, this);
	}
	m_cTcpipDlg->ShowWindow(SW_SHOW);
}


void CMainDlg::OnCmera()
{
	if (m_cGigeCamSettingDlg != nullptr)
	{
		delete m_cGigeCamSettingDlg;
		m_cGigeCamSettingDlg = nullptr;
	}
	if (m_cGigeCamSettingDlg == nullptr)
	{
		m_cGigeCamSettingDlg = new CGigeCamSettingDlg;
		m_cGigeCamSettingDlg->Create(IDD_DIALOG_GIGECAM, this);
	}
	m_cGigeCamSettingDlg->ShowWindow(SW_SHOW);
}




void CMainDlg::OnBnClickedButtonStop()
{
	int nErrCode;
	nErrCode = gSystemMgr.m_cGigeCam.StopGrabbing();//停止采集
	if (MV_OK != nErrCode)
	{
		gSystemLog.DisplayLogAndSave(L"Stop Grabbing Fail!", LV_ERROR);
		return;
	}
	gSystemLog.DisplayLogAndSave(L"Stop Grabbing!", LV_EVENT);
	gSystemMgr.m_maindlgInf.m_bDoOnceMatch = false;
	gSystemMgr.m_maindlgInf.m_bMatchStartFlag = false;
}


int CMainDlg::OnBnClickedButtonStart()
{
	int nErrCode;
	if (gSystemMgr.m_cGigeCam.m_bStartGrabbing)
	{
		return 1;
	}
	if (!gSystemMgr.m_cGigeCam.m_bOpenDevice)
	{
		nErrCode = gSystemMgr.m_cGigeCam.OpenDevice(m_comboCamList.GetCurSel());

		if (MV_OK != nErrCode)
		{
			gSystemLog.DisplayLogAndSave(L"相机占用中...！", LV_ERROR);
			Sleep(5000);
			return 0;
		}
		gSystemMgr.m_cGigeCam.m_nPixelFormat = PixelType_Gvsp_Mono8;
		nErrCode = gSystemMgr.m_cGigeCam.SetPixelFormat();
		if (MV_OK != nErrCode)
		{
			gSystemLog.DisplayLogAndSave(L"相机设置图像格式失败！", LV_ERROR);
			return 0;
		}

		gSystemMgr.m_cGigeCam.m_nTriggerSource = MV_TRIGGER_SOURCE_SOFTWARE;
		nErrCode = gSystemMgr.m_cGigeCam.SetTriggerSource();
		if (MV_OK != nErrCode)
		{
			gSystemLog.DisplayLogAndSave(L"相机设置软件资源失败！", LV_ERROR);
			return 0;
		}


		gSystemMgr.m_cGigeCam.m_nTriggerMode = MV_TRIGGER_MODE_ON;
		nErrCode = gSystemMgr.m_cGigeCam.SetTriggerMode();
		if (MV_OK != nErrCode)
		{
			gSystemLog.DisplayLogAndSave(L"相机设置触发失败！", LV_ERROR);
			return 0;
		}

		gSystemMgr.m_cGigeCam.m_dExpouseEdit = gSystemMgr.m_sCameraInf.m_fExposureTime;
		nErrCode = gSystemMgr.m_cGigeCam.SetExposureTime();
		if (nErrCode != MV_OK)
		{
			gSystemLog.DisplayLogAndSave(L"相机设置曝光失败", LV_ERROR);
			//return 0;
		}
		gSystemLog.DisplayLogAndSave(L"相机设备打开成功！", LV_EVENT);
	}
	nErrCode = gSystemMgr.m_cGigeCam.GigECamRun(m_comboCamList.GetCurSel());

	return 1;
}

unsigned int __stdcall CMainDlg::StartCamCheckThread()
{
	int nErrCode;
	while (true)
	{
		Sleep(3000);
		if (!gSystemMgr.m_cGigeCam.m_bOpenDevice && !gSystemMgr.m_cGigeCam.m_bStartGrabbing)
		{

			gSystemMgr.m_cGigeCam.OpenDevice(m_comboCamList.GetCurSel());

			gSystemMgr.m_cGigeCam.m_nTriggerSource = MV_TRIGGER_SOURCE_SOFTWARE;
			nErrCode = gSystemMgr.m_cGigeCam.SetTriggerSource();
			if (MV_OK != nErrCode)
			{
				gSystemLog.DisplayLogAndSave(L"相机设备打开失败！尝试重新打开！", LV_ERROR);
				continue;
			}

			nErrCode = gSystemMgr.m_cGigeCam.SetPixelFormat();
			if (MV_OK != nErrCode)
			{
				gSystemLog.DisplayLogAndSave(L"相机设置图像格式失败！", LV_ERROR);
				return 0;
			}

			gSystemMgr.m_cGigeCam.m_nTriggerMode = MV_TRIGGER_MODE_ON;
			nErrCode = gSystemMgr.m_cGigeCam.SetTriggerMode();
			if (MV_OK != nErrCode)
			{
				gSystemLog.DisplayLogAndSave(L"相机设备打开失败,尝试重新打开！", LV_ERROR);
				continue;
			}
			gSystemLog.DisplayLogAndSave(L"相机设备打开成功！", LV_EVENT);
			gSystemMgr.m_cGigeCam.GigECamRun(m_comboCamList.GetCurSel());

		}
	}

	return TRUE;
}

void CMainDlg::OnBnClickedButtonInit()
{
	m_comboCamList.ResetContent();
	gSystemMgr.m_cGigeCam.GigECamInit();
	for (unsigned int i = 0; i < gSystemMgr.m_cGigeCam.m_stDevList.nDeviceNum; i++)
	{
		m_comboCamList.AddString(gSystemMgr.m_cGigeCam.m_cstrGigeCamEnumName[i]);
		m_comboCamList.SetCurSel(0);
	}

}

unsigned int __stdcall CMainDlg::CamDisplayThread()
{
	while (1)
	{
		if (!gSystemMgr.m_cGigeCam.m_bStartGrabbing)
		{
			Sleep(10);
			continue;
		}
		Sleep(10);
		//gSystemMgr.m_matImage = gSystemMgr.m_cGigeCam.m_matBmpbuf.clone();

		//if (gSystemMgr.m_maindlgInf.m_bMatchStartFlag)
		//{
		//	gSystemMgr.ShowImage(gSystemMgr.m_matShow, this, IDC_SHOW_IMAGE);
		//}
		//else
		//{
		//	gSystemMgr.ShowImage(gSystemMgr.m_matImage, this, IDC_SHOW_IMAGE);
		//}
	}
}






HBRUSH CMainDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr1 = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);

	DeleteObject(hbr);

	UINT id = pWnd->GetDlgCtrlID();
	CString cstr;

	if (id == IDC_EDIT_RESULT_SHOW)
	{
		GetDlgItem(id)->GetWindowTextW(cstr);
		if (cstr == L"OK")
		{
			hbr = CreateSolidBrush(RGB(0, 255, 0));
		}
		else if (cstr == L"NG")
		{
			hbr = CreateSolidBrush(RGB(255, 0, 0));
		}
		else if (cstr == L"WAIT")
		{
			hbr = CreateSolidBrush(RGB(222, 233, 20));
		}
		pDC->SetBkMode(TRANSPARENT);
	}
	if (id == IDC_STATIC_CAM_STATUS)
	{
		GetDlgItem(id)->GetWindowTextW(cstr);
		if (cstr == L"OK")
		{
			hbr = CreateSolidBrush(RGB(0, 255, 0));
		}
		else if (cstr == L"FAIL")
		{
			hbr = CreateSolidBrush(RGB(255, 0, 0));
		}
		pDC->SetBkMode(TRANSPARENT);
	}
	if (id == IDC_LINK_PLC)
	{
		GetDlgItem(id)->GetWindowTextW(cstr);
		if (cstr == L"OK")
		{
			hbr = CreateSolidBrush(RGB(0, 255, 0));
		}
		else if (cstr == L"FAIL")
		{
			hbr = CreateSolidBrush(RGB(255, 0, 0));
		}
		pDC->SetBkMode(TRANSPARENT);
	}
	// TODO:  在此更改 DC 的任何特性

	// TODO:  如果默认的不是所需画笔，则返回另一个画笔
	hbr1 = hbr;
	return hbr;
}


void CMainDlg::OnTimer(UINT_PTR nIDEvent)
{
	CDialogEx::OnTimer(nIDEvent);
}



void CMainDlg::OnBtnChangeProject()
{
	if (m_cChangeProjectDlg != nullptr)
	{
		delete m_cChangeProjectDlg;
		m_cChangeProjectDlg = nullptr;
	}
	if (m_cChangeProjectDlg == nullptr)
	{
		m_cChangeProjectDlg = new CChangeProjectDlg;
		m_cChangeProjectDlg->Create(IDD_DIALOG_CHANGE_PROJECT, this);
	}
	m_cChangeProjectDlg->ShowWindow(SW_SHOW);
}



void CMainDlg::Repaint(CWnd * pWnd, int last_Width, int now_Width, int last_Height, int now_Height, int cnt)
{
	if (pWnd)
	{
		CRect rect;
		CRect rect2;
		pWnd->GetWindowRect(&rect2);
		rect = OriRect[cnt];
		int n = 62;
		int m = 8;
		//rect2.top = rect2.top - n;
		//rect2.bottom = rect2.bottom - n;
		ScreenToClient(&rect2);

		double proportion_x = now_Width / (double)last_Width;
		double proportion_y = now_Height / (double)last_Height;

		rect.left = (long)(rect.left*proportion_x + 0.5 - m * proportion_x);
		rect.right = (long)(rect.left + RectW[cnt] * proportion_x + 0.5);
		rect.top = (long)(rect.top *proportion_y + 0.5 - n * proportion_y);
		rect.bottom = (long)(rect.top + RectH[cnt] * proportion_y + 0.5);
		pWnd->MoveWindow(&rect);
	}

}

void CMainDlg::OnSize(UINT nType, int cx, int cy)
{
	CDialogEx::OnSize(nType, cx, cy);

	if (0 == m_rcUiRect.left && 0 == m_rcUiRect.right && 0 == m_rcUiRect.top && 0 == m_rcUiRect.bottom)//第一次启动对话框时的大小变化不做处理
	{
	}
	else
	{
		if (0 == cx && 0 == cy)//如果是按下了最小化，则触发条件，这时不保存对话框数据
		{
			return;
		}
		CRect rectDlgChangeSize;
		GetClientRect(&rectDlgChangeSize);//存储对话框大小改变后对话框大小数据

		//if (rectDlgChangeSize.Width() > 400 && rectDlgChangeSize.Height() > 200) {
		CWnd *pWnd;
		int n = 0;


		n = n + 1; pWnd = GetDlgItem(IDC_STATIC_1); Repaint(pWnd, m_rcUiRect.Width(), rectDlgChangeSize.Width(), m_rcUiRect.Height(), rectDlgChangeSize.Height(), n);
		n = n + 1; pWnd = GetDlgItem(IDC_COMBO_CAMLIST); Repaint(pWnd, m_rcUiRect.Width(), rectDlgChangeSize.Width(), m_rcUiRect.Height(), rectDlgChangeSize.Height(), n);
		n = n + 1; pWnd = GetDlgItem(IDC_SHOW_IMAGE); Repaint(pWnd, m_rcUiRect.Width(), rectDlgChangeSize.Width(), m_rcUiRect.Height(), rectDlgChangeSize.Height(), n);
		n = n + 1; pWnd = GetDlgItem(IDC_STATIC_2); Repaint(pWnd, m_rcUiRect.Width(), rectDlgChangeSize.Width(), m_rcUiRect.Height(), rectDlgChangeSize.Height(), n);
		n = n + 1; pWnd = GetDlgItem(IDC_LINK_PLC); Repaint(pWnd, m_rcUiRect.Width(), rectDlgChangeSize.Width(), m_rcUiRect.Height(), rectDlgChangeSize.Height(), n);
		n = n + 1; pWnd = GetDlgItem(IDC_STATIC_CAM_STATUS); Repaint(pWnd, m_rcUiRect.Width(), rectDlgChangeSize.Width(), m_rcUiRect.Height(), rectDlgChangeSize.Height(), n);
		n = n + 1; pWnd = GetDlgItem(IDC_LIST_LOG); Repaint(pWnd, m_rcUiRect.Width(), rectDlgChangeSize.Width(), m_rcUiRect.Height(), rectDlgChangeSize.Height(), n);
		n = n + 1; pWnd = GetDlgItem(IDC_STATIC_3); Repaint(pWnd, m_rcUiRect.Width(), rectDlgChangeSize.Width(), m_rcUiRect.Height(), rectDlgChangeSize.Height(), n);
		n = n + 1; pWnd = GetDlgItem(IDC_EDIT_RESULT_SHOW); Repaint(pWnd, m_rcUiRect.Width(), rectDlgChangeSize.Width(), m_rcUiRect.Height(), rectDlgChangeSize.Height(), n);
		n = n + 1; pWnd = GetDlgItem(IDC_BUTTON_TEST_HAND); Repaint(pWnd, m_rcUiRect.Width(), rectDlgChangeSize.Width(), m_rcUiRect.Height(), rectDlgChangeSize.Height(), n);
			}
	//GetClientRect(&m_rcUiRect); //save size of dialog
	Invalidate();//更新窗口
}

void CMainDlg::OnGlueTest()
{
	if (m_cGlueTestDlg != nullptr)
	{
		delete m_cGlueTestDlg;
		m_cGlueTestDlg = nullptr;
	}
	if (m_cGlueTestDlg == nullptr)
	{
		m_cGlueTestDlg = new CGlueTestDlg;
		m_cGlueTestDlg->Create(IDD_DIALOG_GLUE_TEST, this);
	}
	m_cGlueTestDlg->ShowWindow(SW_SHOW);
}



void CMainDlg::OnBnClickedButtonTestHand()
{
	//gSystemMgr.ImgSaveFlag = 1;
	gSystemMgr.m_bGlueTestStart = true;
	//if (m_cGlueTestDlg == nullptr)
	//{
	//	m_cGlueTestDlg = new CGlueTestDlg;
	//	m_cGlueTestDlg->Create(IDD_DIALOG_GLUE_TEST, this);
	//}
	//StartGlueCheckMainThread();
}

void CMainDlg::StartGlueCheckMainThread()
{
	GlueCheck.MemProc = &CMainDlg::GlueCheckMainThread;
	UINT nThreadId;
	HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, GlueCheck.ThreadProc, (LPVOID)this, 0, &nThreadId);
	if (hThread == NULL)
	{
		gSystemLog.DisplayLogAndSave(L"Create CamDisplay thread fail", LV_ERROR);
	}
}
unsigned int __stdcall CMainDlg::GlueCheckMainThread()
{
	gSystemMgr.m_matImage.release();
	gSystemMgr.m_cGigeCam.DoSoftwareOnce();//抓取一次图像
	int nTime = 50;
	while (gSystemMgr.m_matImage.empty() && nTime-- > 0)
	{
		Sleep(50);
	}
	int nResult = m_cGlueTestDlg->GlueTest(gSystemMgr.m_matImage);
	gSystemMgr.ShowImage(m_cGlueTestDlg->m_matImage_T, this, IDC_SHOW_IMAGE);
	gSystemMgr.SaveTestResult(NULL, nResult, gSystemMgr.m_matImage, m_cGlueTestDlg->m_matImage_T);
	if (m_cGlueTestDlg->m_fGlueTestHand == 1)
	{
		GetDlgItem(IDC_EDIT_RESULT_SHOW)->SetWindowText(L"OK");
	}
	else if (m_cGlueTestDlg->m_fGlueTestHand == 2)
	{
		GetDlgItem(IDC_EDIT_RESULT_SHOW)->SetWindowText(L"NG");
	}
	return 0;
}


void CMainDlg::OnBnClickedButton1()
{

	// TODO:  在此添加控件通知处理程序代码
	IplImage* SrcImg = NULL;
	CFileDialog dlg(TRUE, L"*.bmp;*.jpg;*.tif", NULL,
		OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY,
		L"image files All Files (*.*) |*.*||", NULL);// 选项图片的约定;  
	dlg.m_ofn.lpstrTitle = _T("打开图片");// 打开文件对话框的标题名;(*.bmp; *.jpg) |*.bmp; *.jpg |  
	if (dlg.DoModal() == IDOK)// 判断是否获得图片;  
	{

		if (dlg.GetFileExt() != "bmp" && dlg.GetFileExt() != "jpg"&&dlg.GetFileExt() != "tif"&&dlg.GetFileExt() != "png")
		{
			AfxMessageBox(_T("请选择正确的图片格式！"), MB_OK);
			return;
		}

		m_cstrPath = dlg.GetPathName();// 获取图片路径;  
		USES_CONVERSION;
		m_cPath = T2A(m_cstrPath);
		SrcImg = cvLoadImage(m_cPath);//读取图片、缓存到一个局部变量ipl中;  
		if (!SrcImg)// 判断是否成功载入图片;  
			return;
	}
	gSystemMgr.m_matImage = imread(m_cPath, IMREAD_GRAYSCALE);

	//	cv::Size dst_sz((matImage.cols / 4), (matImage.rows / 4));
	//	cv::resize(matImage, m_matImage, dst_sz);
	/*
	picture control显示图片，picture control的ID为IDC_ShowSrcImg
	*/
	//获取IDC_STATIC控件的设备环境，w以便对其进行图像操作
	CDC* pDCSrc = GetDlgItem(IDC_SHOW_IMAGE)->GetDC();//获得显示空间的DC,MFC类一般都是以C开头
	HDC  hDCSrc = pDCSrc->GetSafeHdc();//得到hDC句柄进行绘图操作
	CvvImage cimgsrc;
	cimgsrc.CopyOf(SrcImg);
	//将图像显示到IDC_ShowImgSrc控件上

	CRect rectsrc;
	GetDlgItem(IDC_SHOW_IMAGE)->GetClientRect(&rectsrc);
	cimgsrc.DrawToHDC(hDCSrc, &rectsrc);
	// 释放
	ReleaseDC(pDCSrc);
}


BOOL CMainDlg::PreTranslateMessage(MSG* pMsg)
{
	// TODO: 在此添加专用代码和/或调用基类
	if (pMsg->wParam == VK_RETURN || pMsg->wParam == VK_ESCAPE)
	{
		return true;
	}
	return CDialogEx::PreTranslateMessage(pMsg);
}
